package org.greyhawk.samonitor.domain;

import javax.persistence.Entity;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.roo.addon.entity.RooEntity;
import org.greyhawk.samonitor.domain.ResourcesType;
import javax.persistence.Enumerated;
import org.greyhawk.samonitor.domain.Site;
import javax.persistence.ManyToOne;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
import javax.persistence.Transient;

import java.util.Date;
import java.util.List;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.springframework.format.annotation.DateTimeFormat;

@Entity
@RooJavaBean
@RooToString
@RooEntity(finders = { "findResourcesesBySummary", "findResourcesesBySite" })
@Table(name = "E_RESOURCES")
public class Resources {

    @Enumerated
    private ResourcesType type;

    private String sourcePath;

    @ManyToOne(targetEntity = Site.class)
    @JoinColumn
    private Site site;

    private String name;

    @Transient
    private byte[] data;

    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(style = "S-")
    private Date createTime;

    private String summary;

    private String text;

    private Boolean isJudge = false;

    @SuppressWarnings("unchecked")
    public static List<Resources> findResourcesBySiteAndType(Site site, ResourcesType type, int startPosition, int maxResult) {
        String qlString = "from Resources res where res.site = :site and res.type = :type and res.isJudge = :isJudge";
        List<Resources> resourcesList = Resources.entityManager().createQuery(qlString).setParameter("site", site)
        .setParameter("type", type).setParameter("isJudge", false).setFirstResult(startPosition).setMaxResults(maxResult).getResultList();
        return resourcesList;
    }

    public static Long findResourcesCountBySiteAndType(Site site, ResourcesType type) {
        String qlString = "select count(*) from Resources res where res.site = :site and res.type = :type and res.isJudge = :isJudge";
        return (Long) Resources.entityManager().createQuery(qlString).setParameter("site", site).setParameter("type", type).setParameter("isJudge", false).getSingleResult();
    }
}
